package com.hoppinzq.service.ftp;


import com.hoppinzq.service.bean.ApiResponse;
import com.hoppinzq.service.common.ftpClientCommon;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:ZhangQi
 **/
@RestController
@RequestMapping("/ftp")
public class FTPController {

    @Autowired
    private FtpUtil ftpUtil;

    @RequestMapping(value = "/ftp", method = RequestMethod.GET)
    @ResponseBody
    public ApiResponse ftp() {
        try{
            MyFTP myFTP=ftpClientCommon.myFTP;
            myFTP.setIp("");
            myFTP.setUsername("");
            myFTP.setPassword("");
            myFTP.setPort("");
            ftpClientCommon.ftpClient = ftpUtil.ftpConnection(myFTP);
            return ApiResponse.data("ok");
        }catch (IOException ioex){
            return ApiResponse.data("文件IO异常" + ioex.getMessage());
        }catch (Exception ex){
            return ApiResponse.data("ftp连接失败" + ex.getMessage());
        }finally {

        }
    }

    @RequestMapping(value = "/getFTPFile", method = RequestMethod.GET)
    @ResponseBody
    public ApiResponse getFTPFile(String dir) {
        FTPClient ftpClient=ftpClientCommon.ftpClient;
        try{
            List list=ftpUtil.getFileList(ftpClient,dir,ftpClientCommon.myFTP.getIp());
            return ApiResponse.data(list);
        }catch (IOException ioex){
            return ApiResponse.data("文件IO异常" + ioex.getMessage());
        }catch (Exception ex){
            return ApiResponse.data("ftp连接失败" + ex.getMessage());
        }finally {
            try{
                ftpUtil.close(ftpClient);
            }catch (Exception ex){
                return ApiResponse.data("ftp关闭失败" + ex.getMessage());
            }
        }
    }


    @RequestMapping(value = "/upFile", method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse upFile(MultipartFile file,String dir) {
        FTPClient ftpClient=ftpClientCommon.ftpClient;
        try{
            String fileRName=null;
            String fileName = file.getOriginalFilename();
            Boolean isEx=ftpUtil.existFile(ftpClient,dir.length()>1?dir+"/"+fileName:dir+fileName);
            if(isEx==true){
                fileRName=fileName.substring(0,fileName.lastIndexOf("."))+new Date().toString();
                ftpUtil.uploadFile(ftpClient,dir,fileRName,file.getInputStream());
            }else{
                ftpUtil.uploadFile(ftpClient,dir,fileName,file.getInputStream());
            }
            Map map=new HashMap();
            map.put("fileChangeName",fileRName);
            map.put("fileName",fileName);
            return ApiResponse.data(map);//成功
        }catch (IOException ioex){
            return ApiResponse.data("文件IO异常" + ioex.getMessage());
        }catch (Exception ex){
            return ApiResponse.data("ftp连接失败" + ex.getMessage());
        }finally {
            try{
                ftpUtil.close(ftpClient);
            }catch (Exception ex){
                return ApiResponse.data("ftp关闭失败" + ex.getMessage());
            }
        }
    }


    @RequestMapping(value = "/checkFTP", method = RequestMethod.GET)
    @ResponseBody
    public ApiResponse checkFTP(@RequestBody MyFTP ftp) {
        FTPClient ftpClient =new FTPClient();
        try {
            ftpClient.connect(ftp.getIp(), Integer.parseInt(ftp.getPort()));
            ftpClient.login(ftp.getUsername(), ftp.getPassword());
            int replyCode = ftpClient.getReplyCode();
            if(replyCode==230){
                ftpUtil.close(ftpClient);
                return ApiResponse.success("可用");
            }else{
                return ApiResponse.success(""+replyCode);
            }
        } catch (SocketException e) {
            return ApiResponse.data("ftp连接失败" + e.getMessage());
        } catch (IOException e) {
            return ApiResponse.data("ftp连接失败" + e.getMessage());
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    public ApiResponse checkFTP(String dir,String fileName) {
        FTPClient ftpClient=ftpClientCommon.ftpClient;
        try {
            Boolean isD=ftpUtil.deleteFile(ftpClient,dir,fileName);
            return ApiResponse.success(""+isD);
        } catch (Exception e) {
            return ApiResponse.data("删除失败" + e.getMessage());
        }
    }


    /**
     *
     * @param dir 文件地址
     * @param fileName 文件名
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public byte[] download(String dir, String fileName) throws IOException {
        FTPClient ftpClient=ftpClientCommon.ftpClient;
        try {
            InputStream is=ftpClient.retrieveFileStream(dir.length()==1?dir+fileName:dir+"/"+fileName);
            byte[] result= IOUtils.toByteArray(is);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftpUtil.close(ftpClient);
        }
        return null;
    }


    /**
     * 下载文件
     * @param dir 文件地址
     * @param fileName 文件名
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    @ResponseBody
    public void downloadFile(HttpServletResponse response,String dir, String fileName) throws IOException {
        byte[] data = this.download(dir,fileName);
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
        response.flushBuffer();
    }

}

